package edu.cuit.campus.web.controller;

import edu.cuit.campus.common.Result;
import edu.cuit.campus.po.Employee;
import edu.cuit.campus.validation.EmployeeValidator;
import edu.cuit.campus.validation.ValidationGroup1;
import edu.cuit.campus.validation.ValidationGroup2;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/15 15:20
 */
@Controller
@RequestMapping("/employees")
public class EmployeeController {
    @InitBinder
    public void initBinder(DataBinder binder){
        //数据绑定器加入验证器
        binder.setValidator(new EmployeeValidator());
    }

    @PostMapping
    @ResponseBody
    public Result save(@Validated(ValidationGroup2.class) @RequestBody Employee employee, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            Map<String, String> errors = new HashMap<>();
            bindingResult.getAllErrors().stream().forEach(e ->
                            errors.put(e.getCodes()[1], e.getDefaultMessage()));
            return Result.fail(errors,"数据校验不通过");
        }

        System.out.println("数据校验通过,调用业务模型");
        return Result.ok(employee);
    }
}
